<template>
	<view class="list" :style="{paddingTop: paddingHeight + 'px'}">
		<nav-bar :title="title"></nav-bar>
		<view class="container">
			<view class="dev_cell" v-for="(item,index) in deviceList" :key="item.deviceId" @click="goDetails(item)">
				<image :class="{disabled: ble.defaultInfo.name !== item.bluetoothName}"
					src="http://oss.antaimedical.com/images/static/2024/05/664f09e6eb14d0f049f44cebLDZqXrRZgSqe11d91b357b29d490d4ba152491082d97.png"
					class="device_mould" />
				<view class="info" :class="{disabled: ble.defaultInfo.name !== item.bluetoothName}">
					<view class="name">
						{{ item.bluetoothName }}
					</view>
					<view class="i-c" v-if="ble.defaultInfo.name == item.bluetoothName">
						<text class="battery" v-if="ble.defaultInfo.battery">{{ ble.defaultInfo.battery }}%</text>
						<u-loading-icon v-else size="14" :show="true"></u-loading-icon>
						<text class="iconfont icon-dianliang"></text>
						<text class="line"></text>
						<text v-if="ble.defaultInfo.version ">v{{ ble.defaultInfo.version }}</text>
						<u-loading-icon v-else size="14" :show="true"></u-loading-icon>
						<text class="line"></text>
						<text class="iconfont icon-lanya"></text>
					</view>
					<view class="i-c" v-else>
						<text class="iconfont icon-lanya"></text>
					</view>
				</view>
				<image
					src="http://oss.antaimedical.com/images/static/2024/06/66693c9feb14d0f049f44d08qDvh2MXpbReMf7cb11a4d2d169395bc6e8abb8fc079c.png"
					class="connect_b" @click.stop="$u.throttle(setCurrentName(item), 2000)"
					v-if="ble.defaultInfo.name !== item.bluetoothName && ble.BleConnectedName !== item.bluetoothName" />
				<view class="connecting" v-else-if="item.bluetoothName === ble.BleConnectedName">
					<text class="l-t">连接中</text>
					<u-loading-icon size="16"></u-loading-icon>
				</view>
				<text class="iconfont icon-arrow_rigth"></text>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		getDeviceByUser
	} from '@/api/index.js'
	import {
		mapState
	} from 'vuex'
	const BLE = require('@/utils/ble.js');
	export default {
		data() {
			return {
				paddingHeight: uni.getStorageSync('navbarHeight'),
				userId: uni.getStorageSync('userId'),
				title: '',
				deviceList: [],
				currentInfo: undefined
			}
		},
		computed: {
			...mapState({
				ble: state => state.ble, // 实时蓝牙全局状态
				userInfo: state => state.userInfo
			})
		},
		watch: {
			'ble.state': {
				handler(nVal, oVal) {
					// 监听蓝牙连接状态事件 如监听到一个连接成功清空当前要搜索的仪器
					if (nVal == 0 || nVal == -3) {
						this.currentInfo = undefined
					}
				}
			}
		},
		onShow() {
			this.fetchDeviceData()
		},
		methods: {
			// 设置连接仪器 准备开始搜索
			setCurrentName(info) {
				this.currentInfo = info
				if (this.ble.state == 0 && this.ble.defaultInfo.name != info.bluetoothName) {
					wx.closeBLEConnection({ // 断开
						deviceId: this.ble.devID,
						complete: () => {
							uni.$u.throttle(this.checkBleStatus(), 2500)
						}
					})
				} else {
					uni.$u.throttle(this.checkBleStatus(), 2500)
				}
			},
			// 开始搜索连接仪器 并设置当前进行搜索的仪器名称
			connect() {
				console.log('列表连接');
				if (uni.$u.os() == 'android') { // 安卓系统直接连接
					this.$store.commit('setDefaultInfo', {
						type: 1,
						data: {
							mac: this.currentInfo.deviceMac,
							name: this.currentInfo.bluetoothName
						}
					})
					BLE.common.createBLEConnectionFn(this.currentInfo.deviceMac, this.currentInfo)
				} else { // 苹果系统需要搜索uuid仪器id
					BLE.common.myStartBluetoothDevicesDiscovery(10000, this.currentInfo)
				}
				this.$store.commit('setBleConnectedName', this.currentInfo.bluetoothName)
			},
			// 获取已绑定仪器信息
			async fetchDeviceData(info) {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					userId: this.userId,
					urlencoded: true
				}
				try {
					const res = await getDeviceByUser(params)
					if (res.code == 200) {
						if (res.data.length) {
							this.deviceList = res.data
							this.title = `所有仪器(${this.deviceList.length})`
						} else {
							uni.$emit('refreshDevice')
							uni.navigateBack()
						}
					}
				} catch (e) {
					//TODO handle the exception
				}
				uni.hideLoading()
			},
			checkBleStatus() {
				let that = this
				if (this.ble.isOpenBleAdapter) {
					wx.getBluetoothAdapterState({
						success: res => {
							if (!res.available) {
								uni.showModal({
									title: '提示',
									content: '检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
									showCancel: false,
									confirmColor: '#545DDE'
								})
							} else {
								that.connect()
							}
						},
						fail: err => {
							uni.showModal({
								title: '提示',
								content: '蓝牙功能异常，请重新进入小程序',
								showCancel: false
							})
						}
					})
				} else {
					wx.closeBluetoothAdapter()
					wx.openBluetoothAdapter({
						success(BleObj) {
							that.$store.commit('changeIsOpenBleAdapter', true)
							that.connect()
						},
						fail(err) {
							console.log('openBluetoothAdapter', err)
							if (err.errCode == 10001) {
								that.$store.commit('changeIsOpenBleAdapter', true)
								uni.showModal({
									title: '提示',
									content: '检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
									showCancel: false,
									confirmColor: '#545DDE'
								})
							}
							if (err.errMsg == 'openBluetoothAdapter:fail auth deny') {
								uni.showModal({
									title: '提示',
									content: '请先授权蓝牙权限',
									confirmColor: '#545DDE',
									success(modal_res) {
										if (modal_res.confirm) {
											wx.openSetting({
												success: (authData) => {
													if (authData.authSetting[
															'scope.bluetooth']) {
														that.checkBleStatus()
													} else { // 未授权
														uni.showModal({
															title: '提示',
															content: '授权失败,您将无法使用蓝牙相关服务',
															confirmColor: '#545DDE',
															showCancel: false,
															success(modal) {
																if (modal
																	.confirm) {
																	wx.closeBluetoothAdapter()
																	that.$store.commit(
																		'changeIsOpenBleAdapter',
																		false)
																}
															}
														})

													}
												}
											})
										} else {
											uni.showModal({
												title: '提示',
												content: '授权失败,您将无法使用蓝牙相关服务',
												confirmColor: '#545DDE',
												showCancel: false,
												success(modal) {
													if (modal.confirm) {
														wx.closeBluetoothAdapter()
														that.$store.commit(
															'changeIsOpenBleAdapter',
															false)
													}
												}
											})
										}
									}
								})
							}
						}
					})
				}
			},
			goDetails(info) {
				if (this.ble.state === -2) return
				uni.navigateTo({
					url: `/pagesA/device/details/index?details=${JSON.stringify(info)}&type=list`
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #FAFAFA !important;
		min-height: 100%;
	}
</style>
<style lang="scss" scoped>
	.list {
		padding: 48rpx 46rpx;

		.container {
			margin-top: 48rpx;

			.dev_cell {
				width: 100%;
				height: 140rpx;
				padding: 0 36rpx 0 48rpx;
				border-radius: 32rpx;
				background-color: #fff;
				margin-bottom: 16rpx;
				display: flex;
				align-items: center;


				.device_mould {
					width: 36rpx;
					height: 86rpx;
					margin-right: 46rpx;
				}

				.info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: center;

					.name {
						text-align: left;
						font-size: 28rpx;
						color: #333333;
					}

					.i-c {
						display: flex;
						align-items: center;
						font-size: 20rpx;
						color: #666;
						margin-top: 12rpx;


						.icon-dianliang {
							color: #7CD37E;
							font-size: 18rpx;
							padding-left: 4rpx;
						}

						.line {
							width: 1rpx;
							height: 22rpx;
							background-color: rgba(#000, .1);
							margin: 0 8rpx;
						}

						.icon-lanya {
							color: #666666;
							font-size: 20rpx;
						}
					}
				}

				.disabled {
					opacity: .3;
				}

				.connect_b {
					width: 128rpx;
					height: 44rpx;
					margin-right: 30rpx;
				}

				.connecting {
					margin-right: 30rpx;
					display: flex;
					align-items: center;

					.l-t {
						font-size: 28rpx;
						color: #333333;
						padding-right: 10rpx;
					}
				}

				.icon-arrow_rigth {
					font-size: 38rpx;
					color: rgba(#666666, .5);
				}
			}
		}

	}
</style>